package net.tycmc.cty.ctyms.timejob.function.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import net.tycmc.bulb.common.util.StringUtil;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
/**
 * 网络文件下载
 * @author chengshichao
 * 创建时间：2013-3-23
 */
public class DownLoadNet {
	
	/**
	 * 下载简单的网络文件
	 * @param netUrl
	 * @return
	 */
	public static String downloadNetSimple(String netUrl) {
		StringBuffer retBuff = new StringBuffer();
		
		if(StringUtil.isNullOrEmpty(netUrl)){
			BufferedReader br = null;
			InputStream inStream = null;
			URL url = null;
			try {
				url = new URL(netUrl);
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			}
			
			try {
				URLConnection conn = url.openConnection();
				inStream = conn.getInputStream();
				br = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
				String line = null;
				while((line = br.readLine()) != null){
					retBuff.append(line);
				}
			} catch (FileNotFoundException e) {
				//e.printStackTrace();
				System.out.println("天气网接口获取数据失败！！！");
			} catch (IOException e) {
				//e.printStackTrace();
				System.out.println("天气网接口获取数据失败！！！");
			}finally{
				try {
					if(br != null)
						br.close();
					if(inStream != null)
						inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return retBuff.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static void main(String[]args){
		String s = downloadNetSimple("http://m.weather.com.cn/data/101010100.html");
		ObjectMapper objectMapper= new ObjectMapper();
		try {
			Map map = objectMapper.readValue(s,Map.class);
			Map<String,Object> map2 = (Map<String,Object>)map.get("weatherinfo");
			System.out.println(map2.get("img_title10"));
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
